<template>
	<view class="record-kpi">
		<view class="date-range">
			<view class="date-range-mask" @click.stop="handleOpenDatePicker"></view>
			<uni-datetime-picker v-model="range" ref="uniDateTimePicker" type="daterange" :clear-icon="false"
				:border="false" @change="dateChange" @maskClick="maskClick" />
		</view>
		<view v-show="isChartShow">
			<view class="screen-kpi-section">
				<view class="record-kpi-type" @click.stop="handleToggleProject">
					<text class="record-kpi-type-text">{{currentProjectName}}</text>
					<van-icon class="arrow-icon" name="arrow-down" />
				</view>

				<view class="record-kpi-type member" @click.stop="handleToggleRole">
					<text class="record-kpi-type-text">{{currentRoleName}}</text>
					<van-icon class="arrow-icon" name="arrow-down" />
				</view>

				<view class="record-kpi-type member" @click.stop="handleToggleMember">
					<text class="record-kpi-type-text">{{currentMemberName}}</text>
					<van-icon class="arrow-icon" name="arrow-down" />
				</view>
			</view>

			<view class="record-kpi-finish-total">
				<view class="header-circle">
					<view class="finish-circle-chart-title">完成率</view>
					<view class="finish-circle-chart">
						<qiun-data-charts type="gauge" :opts="opts" :chartData="chartData" />
					</view>
				</view>
				<view class="bottom-total-statics">
					<view class="statics-item">
						<view class="statics-value-text text1">{{staticsData.total}}</view>
						<view class="statics-value-title">工作项总数</view>
					</view>
					<view class="statics-item">
						<view class="statics-value-text text2">{{staticsData.finish}}</view>
						<view class="statics-value-title">已完成</view>
					</view>
					<view class="statics-item">
						<view class="statics-value-text text3">{{staticsData.unfinished}}</view>
						<view class="statics-value-title">未完成</view>
					</view>
				</view>
			</view>

			<view class="record-kpi-item">
				<view class="record-kpi-item-title">板块分布统计</view>
				<view class="record-kpi-item-chart" :style="{'height': projectKPIheight + 'px'}"
					v-if="isProjectKPIshow">
					<qiun-data-charts type="bar" :opts="projectDistriOpts" :chartData="projectDistriChartData"
						@tap="handleProjectTap($event)" />
				</view>

				<view class="record-kpi-item-chart" v-else>
					<view class="record-kpi-item-chart-tips">
						<image class="no-data-img" src="../../static/no-data.png" mode="widthFix"></image>
						<text class="tips-text">暂无数据</text>
					</view>
				</view>
			</view>

			<view class="record-kpi-item">
				<view class="record-kpi-item-title">成员结果分布统计</view>
				<view class="record-kpi-item-chart" :style="{'height': memberKPIheight + 'px'}" v-if="isMemberKPIshow">
					<qiun-data-charts type="bar" :opts="memberOpts" :ontouch="true" :chartData="memberChartData" />
				</view>

				<view class="record-kpi-item-chart" v-else>
					<view class="record-kpi-item-chart-tips">
						<image class="no-data-img" src="../../static/no-data.png" mode="widthFix"></image>
						<text class="tips-text">暂无数据</text>
					</view>
				</view>
			</view>

			<view class="record-kpi-item">
				<view class="record-kpi-item-title date-item-title">
					<view>日期分布统计</view>
					<view class="year">{{currentYear}}年</view>
				</view>
				<view class="record-kpi-item-chart date-item-chart" v-if="isDateKPIshow">
					<qiun-data-charts type="area" :opts="dateOpts" :ontouch="true" :chartData="dateChartData" />
				</view>
				<view class="record-kpi-item-chart" v-else>
					<view class="record-kpi-item-chart-tips">
						<image class="no-data-img" src="../../static/no-data.png" mode="widthFix"></image>
						<text class="tips-text">暂无数据</text>
					</view>
				</view>
			</view>

			<view class="height"></view>
		</view>


		<!-- 切换项目类别popup -->
		<van-popup :show="projectTypePopShow" position="bottom">
			<van-picker show-toolbar :columns="projectTypeList" @confirm="onProjectTypeConfirm"
				@cancel="onProjectTypeCancel" />
		</van-popup>

		<!-- 切换岗位popup -->
		<van-popup :show="rolePopShow" position="bottom">
			<van-picker show-toolbar :columns="roleTypeList" @confirm="onRoleConfirm" @cancel="onRoleCancel" />
		</van-popup>

		<!-- 切换成员popup -->
		<van-popup :show="memberPopShow" position="bottom">
			<van-picker show-toolbar :columns="memberTypeList" @confirm="onMemberConfirm" @cancel="onMemberCancel" />
		</van-popup>
	</view>
</template>

<script>
	import apiRqs from "@/api/api-request.js";
	import getDateTime from '@/common/getDateTime.js';
	import removeDuplication from '@/common/removeDuplication.js';
	export default {
		data() {
			return {
				shopId: "",
				projectList: [],
				projectTypeList: [],
				projectTypeIdList: [],
				projectTypePopShow: false,
				memberList: [],
				memberPopShow: false,
				memberTypeList: [],
				memberTypeIdList: [],
				rolePopShow: false,
				roleList: [],
				roleTypeList: [],
				roleTypeIdList: [],
				projectTypeValue: "",
				projectTypeIdValue: "",
				memberTypeValue: "",
				memberTypeIdValue: "",
				currentProjectName: "",
				currentProjectId: "",
				currentRoleName: "全部岗位",
				currentRoleId: "0",
				currentMemberName: "全部人员",
				currentMemberId: ["0"],
				range: [],
				chartData: {},
				projectDistriChartData: {},
				memberChartData: {},
				dateChartData: {},
				isProjectKPIshow: true,
				isMemberKPIshow: true,
				isDateKPIshow: true,
				opts: {
					color: ["#008aff", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: undefined,
					title: {
						name: "",
						fontSize: 22,
						color: "#008aff",
						offsetY: -6
					},
					subtitle: {
						name: "",
						fontSize: 15,
						color: "#008aff",
						offsetY: 0
					},
					extra: {
						gauge: {
							type: "progress",
							width: 10,
							labelColor: "#666666",
							startAngle: 0.75,
							endAngle: 0.25,
							startNumber: 0,
							endNumber: 100,
							labelFormat: "",
							splitLine: {
								fixRadius: 0,
								splitNumber: 8,
								width: 8,
								color: "#FFFFFF",
								childNumber: 5,
								childWidth: 12
							},
							pointer: {
								width: 24,
								color: "auto"
							}
						}
					}
				},
				projectDistriOpts: {
					color: ["#008aff", "#D4DEEC", "#91CB74", "#FAC858", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 30, 0, 5],
					legend: {},
					xAxis: {
						boundaryGap: "justify",
						disableGrid: false,
						fontSize: 12,
						min: 0,
						axisLine: false,
						axisLineColor: "#EEEEEE",
						gridColor: "#EEEEEE",
						fontColor: "#FFFFFF",
					},
					yAxis: {
						type: 'categories',
						format: "tooltipLength",
					},
					extra: {
						bar: {
							type: "stack",
							width: 20,
							meterBorde: 1,
							meterFillColor: "#FFFFFF",
							activeBgColor: "#000000",
							linearType: "opacity",
							activeBgOpacity: 0.08,
							seriesGap: 8,
							categoryGap: 2
						}
					}
				},
				memberOpts: {
					color: ["#008aff", "#D4DEEC", "#91CB74", "#FAC858", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 30, 0, 5],
					legend: {},
					xAxis: {
						boundaryGap: "justify",
						disableGrid: false,
						fontSize: 12,
						min: 0,
						axisLine: false,
						axisLineColor: "#EEEEEE",
						gridColor: "#EEEEEE",
						fontColor: "#FFFFFF",
					},
					yAxis: {
						type: 'categories',
						format: "tooltipLength",
					},
					extra: {
						bar: {
							type: "stack",
							width: 20,
							meterBorde: 1,
							meterFillColor: "#FFFFFF",
							activeBgColor: "#000000",
							linearType: "opacity",
							activeBgOpacity: 0.08,
							seriesGap: 8,
							categoryGap: 2
						}
					}
				},
				dateOpts: {
					color: ["#6F97D2", "#33D1C9", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
						"#ea7ccc"
					],
					padding: [15, 15, 0, 15],
					legend: {},
					xAxis: {
						disableGrid: true,
						fontSize: 10,
					},
					yAxis: {
						gridType: "dash",
						dashLength: 2
					},
					extra: {
						area: {
							type: "curve",
							opacity: 0.8,
							addLine: true,
							width: 2,
							gradient: true
						}
					}
				},
				rqsData: {
					"shopId": "",
					"dateRange": {
						"beginDate": "",
						"endDate": ""
					},
					"tempId": "0",
					"userId": [
						"0"
					]
				},
				staticsData: {},
				currentYear: "",
				projectKPIheight: 240,
				memberKPIheight: 240,
				isChartShow: true,
			}
		},
		onReady() {
			this.getDateData();
		},
		onShow() {
			const tokenInfo = uni.getStorageSync("tokenInfo");
			var timeStr = getDateTime.dateTimeStr('y-m-d'); // y:年 m:月 d:日 h:时 i:分 s:秒 中间的分割符号可更改
			this.range[0] = timeStr + " 00:00:00";
			this.range[1] = timeStr + " 00:00:00";
			this.rqsData.dateRange.beginDate = timeStr + " 00:00:00";
			this.rqsData.dateRange.endDate = timeStr + " 00:00:00";
			this.rqsData.shopId = tokenInfo.shopId;
			this.shopId = tokenInfo.shopId;
			this.handleGetMemberList();
			this.handleGetProjectList();
		},
		onLoad() {
			getApp().showLoading();
			this.handleGetProjectList();
		},
		methods: {
			handleOpenDatePicker() {
				this.$refs.uniDateTimePicker.show();
				this.isChartShow = false;
			},
			maskClick() {
				this.isChartShow = true;
			},
			handleProjectTap(e) {
				console.log('chart tap', e);
			},
			dateChange(e) {
				this.range[0] = e[0] + " 00:00:00";
				this.range[1] = e[1] + " 00:00:00";
				console.log('Click:', this.range);
				getApp().showLoading();
				this.isChartShow = true;
				this.handleProjectStatics();
				this.getProjectDistriData();
				this.getMemberData();
				this.getDateData();
			},
			// 获取项目完成度总览
			handleProjectStatics() {
				let rqs = {
					"shopId": this.shopId,
					"dateRange": {
						"beginDate": this.range[0],
						"endDate": this.range[1]
					},
					"tempId": this.currentProjectId,
					"userId": this.currentMemberId
				};
				apiRqs._getKPIstatics(rqs).then((res) => {
					console.log('完成度总览', res);
					uni.hideLoading();
					if (res.code == 200) {
						this.staticsData = res.data;
						let rate = res.data.finishRate;
						let chartRes = {
							categories: [{
								"value": 0.2,
								"color": "#f04864"
							}, {
								"value": 0.8,
								"color": "#2fc25b"
							}, {
								"value": 1,
								"color": "#008aff"
							}],
							series: [{
								name: "完成率",
								data: rate
							}]
						};

						this.opts.title.name = (rate * 100).toFixed(0) + "%";
						this.chartData = JSON.parse(JSON.stringify(chartRes));
					} else {
						getApp().showToast(res.msg);
					}
				}).catch((err) => {
					console.log('err', err);
				})
			},
			// 切换项目
			handleToggleProject() {
				this.projectTypePopShow = true;
				this.isChartShow = false;
			},
			// 切换岗位
			handleToggleRole() {
				this.rolePopShow = true;
				this.isChartShow = false;
			},
			// 切换成员
			handleToggleMember() {
				this.memberPopShow = true;
				this.isChartShow = false;
			},
			// 获取项目列表
			async handleGetProjectList() {
				var that = this;
				await apiRqs._getShopTemplateList({
					"pageSize": 999,
					"pageIndex": 1,
					"orderBy": ""
				}).then((res) => {
					console.log('项目列表', res);
					if (res.code == 200) {
						let projectTypeList = [];
						let projectTypeIdList = [];
						let data = res.data.data;
						that.projectList = res.data.data;
						that.currentProjectName = "全部项目";
						that.rqsData.tempId = "0";
						that.currentProjectId = "0";
						for (let i = 0; i < data.length; i++) {
							projectTypeList.push(data[i].name);
							projectTypeIdList.push(data[i].id);
						}
						projectTypeList.unshift("全部项目");
						projectTypeIdList.unshift("0");
						that.projectTypeList = projectTypeList;
						that.projectTypeIdList = projectTypeIdList;
						that.handleProjectStatics();
						that.getProjectDistriData();
						that.getMemberData();
						that.getDateData();
					}
				}).catch((err) => {
					console.log('err', err)
				})
			},
			// 获取用户列表
			async handleGetMemberList() {
				var that = this;
				await apiRqs._getUser().then((res) => {
					console.log('成员列表', res);
					if (res.code == 200) {
						that.memberList = res.data;
						let memberList = [];
						let memberIdList = [];
						let roleList = [];
						let roleIdList = [];
						let data = res.data;
						for (let i = 0; i < data.length; i++) {
							memberList.push(data[i].realName);
							memberIdList.push(data[i].userId);
							roleList.push(data[i].roleName);
						}
						let newRoleList = removeDuplication.unique(roleList);
						// 获取去重的roleId
						// for (let i = 0; i < newRoleList.length; i++) {
						// 	for (let y = 0; y < data.length; y++) {
						// 		if (newRoleList[i] === data[y].roleName) {
						// 			roleIdList.push(data[y].roleId);
						// 			break;
						// 		}
						// 	}
						// }
						newRoleList.unshift("全部岗位");
						that.roleTypeList = newRoleList;
						memberList.unshift("全部人员");
						memberIdList.unshift("0");
						that.memberTypeList = memberList;
						that.memberTypeIdList = memberIdList;
					}
				}).catch((err) => {
					console.log('err', err)
				})
			},

			onProjectTypeConfirm(value) {
				console.log(value);
				this.projectTypeValue = value.detail.value;
				this.projectTypeIdValue = this.projectTypeIdList[value.detail.index];
				this.currentProjectName = value.detail.value;
				this.currentProjectId = this.projectTypeIdList[value.detail.index];
				this.projectTypePopShow = false;
				this.isChartShow = true;
				getApp().showLoading();
				this.handleProjectStatics();
				this.getProjectDistriData();
				this.getMemberData();
				this.getDateData();
			},
			onProjectTypeCancel() {
				this.projectTypePopShow = false;
				this.isChartShow = true;
			},
			onMemberConfirm(value) {
				console.log(value);
				this.memberTypeValue = value.detail.value;
				this.memberIdValue = this.memberTypeIdList[value.detail.index];
				this.currentMemberName = value.detail.value;
				this.currentMemberId = [this.memberTypeIdList[value.detail.index]];
				this.memberPopShow = false;
				this.isChartShow = true;
				getApp().showLoading();
				this.handleProjectStatics();
				this.getProjectDistriData();
				this.getMemberData();
				this.getDateData();
			},
			onMemberCancel() {
				this.memberPopShow = false;
				this.isChartShow = true;
			},
			onRoleConfirm(value) {
				console.log(value);
				this.currentRoleName = value.detail.value;
				let memberTypeList = [];
				let memberTypeIdList = [];
				for (let i = 0; i < this.memberList.length; i++) {
					if (value.detail.value === this.memberList[i].roleName) {
						memberTypeList.push(this.memberList[i].realName);
						memberTypeIdList.push(this.memberList[i].userId);
					}
				}
				this.memberTypeList = memberTypeList;
				this.memberTypeIdList = memberTypeIdList;
				this.currentMemberId = memberTypeIdList;
				this.currentMemberName = "全部人员";
				this.rolePopShow = false;
				this.isChartShow = true;
				getApp().showLoading();
				this.handleProjectStatics();
				this.getProjectDistriData();
				this.getMemberData();
				this.getDateData();
			},
			onRoleCancel() {
				this.rolePopShow = false;
				this.isChartShow = true;
			},
			// 板块分布统计
			getProjectDistriData() {
				let rqs = {
					"shopId": this.shopId,
					"dateRange": {
						"beginDate": this.range[0],
						"endDate": this.range[1]
					},
					"tempId": this.currentProjectId,
					"userId": this.currentMemberId
				};
				apiRqs._getKPItemResult(rqs).then((res) => {
					console.log('板块分布统计', res);
					let maxSeries = [];
					let series = JSON.parse(JSON.stringify(res.data.series));
					for (let i = 0; i < series.length; i++) {
						series[i].format = 'seriesFormat';
						if (i == 0) {
							series[i].textOffset = 20;
							// res.data.series[i].textColor = "#fff"
						} else if (i == 1) {
							series[i].textOffset = 0;
						}
						for (let j = 0; j < series[i].data.length; j++) {
							if (!maxSeries[j]) {
								maxSeries[j] = series[i].data[j]
							} else {
								maxSeries[j] = maxSeries[j] + series[i].data[j];
							}
						}
					}
					let maxSplitNumber = Math.max(...maxSeries);
					this.projectDistriOpts.xAxis.splitNumber = maxSplitNumber > 5 ? 5 : 3;
					this.projectDistriOpts.xAxis.max = maxSplitNumber;
					this.projectKPIheight = res.data.xAxis.length > 3 ? res.data.xAxis.length * 70 : 240;
					if (res.code == 200) {
						if (res.data.xAxis.length == 0) {
							this.isProjectKPIshow = false;
						} else {
							this.isProjectKPIshow = true;
							let chartRes = {
								categories: res.data.xAxis,
								series: series
							};
							this.projectDistriChartData = JSON.parse(JSON.stringify(chartRes));
						}
					} else {
						getApp().showToast(res.msg);
					}
				}).catch((err) => {
					console.log('err', err);
				})
			},
			// 成员结果分布统计
			getMemberData() {
				let rqs = {
					"shopId": this.shopId,
					"dateRange": {
						"beginDate": this.range[0],
						"endDate": this.range[1]
					},
					"tempId": this.currentProjectId,
					"userId": this.currentMemberId
				};
				apiRqs._getKPImemberResult(rqs).then((res) => {
					console.log('成员结果分布统计', res);
					let maxSeries = [];
					let series = JSON.parse(JSON.stringify(res.data.series));
					for (let i = 0; i < series.length; i++) {
						series[i].format = 'seriesFormat';
						if (i == 0) {
							series[i].textOffset = 20;
							// res.data.series[i].textColor = "#fff"
						} else if (i == 1) {
							series[i].textOffset = 0;
						}
						for (let j = 0; j < series[i].data.length; j++) {
							if (!maxSeries[j]) {
								maxSeries[j] = series[i].data[j]
							} else {
								maxSeries[j] = maxSeries[j] + series[i].data[j];
							}
						}
					}
					let maxSplitNumber = Math.max(...maxSeries);
					this.memberOpts.xAxis.splitNumber = maxSplitNumber > 5 ? 5 : 3;
					this.memberOpts.xAxis.max = maxSplitNumber;
					this.memberKPIheight = res.data.xAxis.length > 3 ? res.data.xAxis.length * 70 : 240;
					if (res.code == 200) {
						if (res.data.xAxis.length == 0) {
							this.isMemberKPIshow = false;
						} else {
							this.isMemberKPIshow = true;
							let chartRes = {
								categories: res.data.xAxis,
								series: series
							};
							this.memberChartData = JSON.parse(JSON.stringify(chartRes));
						}
					} else {
						getApp().showToast(res.msg);
					}
				}).catch((err) => {
					console.log('err', err);
				})
			},

			// 日期分布统计
			getDateData() {
				let rqs = {
					"shopId": this.shopId,
					"dateRange": {
						"beginDate": this.range[0],
						"endDate": this.range[1]
					},
					"tempId": this.currentProjectId,
					"userId": this.currentMemberId
				};
				apiRqs._getKPIdateResult(rqs).then((res) => {
					console.log('日期分布统计', res);
					let maxSeries = [];
					for (let i = 0; i < res.data.series.length; i++) {
						maxSeries[i] = Math.max(...res.data.series[i].data);
					}
					let maxSplitNumber = Math.max(...maxSeries);
					this.dateOpts.yAxis.splitNumber = maxSplitNumber > 5 ? 5 : 3;
					if (res.code == 200) {
						if (res.data.xAxis.length == 0) {
							this.isDateKPIshow = false;
						} else {
							let newX = [];
							let currentYear = "";
							for (let i = 0; i < res.data.xAxis.length; i++) {
								currentYear = res.data.xAxis[i].split("-")[0];
								newX.push(res.data.xAxis[i].split("-")[1] + "." + res.data.xAxis[i].split("-")[2])
							}

							this.isDateKPIshow = true;
							this.currentYear = currentYear;
							let chartRes = {
								categories: newX,
								series: res.data.series
							};
							this.dateChartData = JSON.parse(JSON.stringify(chartRes));
						}
					} else {
						getApp().showToast(res.msg);
					}
				}).catch((err) => {
					console.log('err', err);
				})
			},
		},
	}
</script>

<style lang="less">
	page {
		background-color: #f5f5f5;
	}

	.record-kpi {
		.date-range {
			position: relative;

			.date-range-mask {
				position: absolute;
				width: 100%;
				height: 35px;
				top: 0;
				left: 0;
				z-index: 90;
				background-color: transparent;
			}

			.uni-datetime-picker {
				position: absolute;
				top: 0;
				left: 0;
			}
		}

		.screen-kpi-section {
			margin: 15px;
			font-size: 14px;
			color: #A0A2AE;
			display: flex;
			align-items: center;

			.record-kpi-type {
				display: flex;
				align-items: center;

				&.member {
					margin-left: 20px;
				}
			}

			.arrow-icon {
				font-size: 12px;
				margin-left: 3px;
			}
		}


		.record-kpi-finish-total {
			background-color: #fff;
			border-radius: 4px;
			margin: 0 15px;
			padding: 15px;

			.header-circle {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;

				.finish-circle-chart-title {
					font-size: 15px;
					font-weight: 500;
					color: #212D53;
				}

				.finish-circle-chart {
					width: 100%;
					height: 150px;
					margin-top: 15px;
				}
			}

			.bottom-total-statics {
				display: flex;
				align-items: center;
				margin-top: 20px;

				.statics-item {
					flex: 1;
					min-width: 0;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					.statics-value-text {
						font-size: 24px;
						font-weight: 600;

						&.text1 {
							color: #5182C6;
						}

						&.text2 {
							color: #859FD7;
						}

						&.text3 {
							color: #67CBD3;
						}
					}

					.statics-value-title {
						margin-top: 5px;
						font-size: 13px;
						color: #C1C0C3;
					}
				}
			}
		}

		.record-kpi-item {
			background-color: #fff;
			border-radius: 4px;
			margin: 0 15px;
			padding: 15px;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-top: 15px;

			.record-kpi-item-title {
				text-align: center;
				font-size: 15px;
				font-weight: 500;
				color: #212D53;

				&.date-item-title {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;

					.year {
						font-size: 12px;
						color: #999;
						margin-top: 5px;
					}
				}
			}

			.record-kpi-item-chart {
				width: 100%;
				height: 200px;
				margin-top: 20px;

				&.date-item-chart {
					height: 280px;
				}

				&.item-chart-top {
					margin-top: 120px;
				}

				.record-kpi-item-chart-tips {
					font-size: 14px;
					color: #999;
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					.no-data-img{
						width: 120px;
						margin-top: 30px;
					}
					.tips-icon {
						font-size: 40px;
					}

					.tips-text {
						margin-top: 20px;
					}
				}
			}
		}

		.height {
			height: 40px;
		}
	}
</style>
